package com.zja.servlet;


import com.zja.model.JsonResponse;
import com.zja.model.User;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author JA
 * @date: 2025/5/3
 * description:获取当前登录信息
 */
@WebServlet("/api/auth/current")
public class CurrentUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");


        User user = (User) req.getSession().getAttribute("currentUser");


        if (user != null) {
            // 构造返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("id", user.getId());
            data.put("username", user.getUsername());
            data.put("email", user.getEmail());
            data.put("role", user.getRole());

            ServletUtil.writeJsonResponse(resp, JsonResponse.success("用户已登录",data));
        } else {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("用户未登录"));
        }
    }
}
